package com.sfac.javaSpringBoot.modules.account.service.Impl;

import com.sfac.javaSpringBoot.modules.account.dao.UserDao;
import com.sfac.javaSpringBoot.modules.account.dao.UserRepository;
import com.sfac.javaSpringBoot.modules.account.entity.User;
import com.sfac.javaSpringBoot.modules.account.service.UserService;
import com.sfac.javaSpringBoot.modules.common.entity.Result;
import com.sfac.javaSpringBoot.modules.common.entity.SearchBean;
import com.sfac.javaSpringBoot.modules.test.entity.Student;
import com.sfac.javaSpringBoot.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.naming.event.ObjectChangeListener;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    UserRepository userRepository;
    @Autowired
    private EntityManager entityManager;


    @Override
    @Transactional
    public Result<User> insertUser(User users) {
        users.setCreateDate(LocalDateTime.now());
        userDao.insertUser(users);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "Insert success",users);
    }

    @Override
    @Transactional
    public Result<User> updateUser(User user) {
        userDao.updateUser(user);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "Update success",user);
    }

    @Override
    @Transactional
    public Result<User> deleteUserById(int id) {
        userDao.deleteUser(id);
        return new Result<>(Result.ResultCode.SUCCESS.code,
        "delete success");
    }

    @Override
    public User findFirstByUserNameAndEmail(String name, String email) {
        return  userRepository.findFirstByUserNameAndEmail(name,email);
    }

    @Override
    @Transactional
    public Result<Object> insertUsers(List<User> users) {
        users.stream().forEach(item->{
                entityManager.persist(item);
        });
        entityManager.flush();
        entityManager.clear();
        return new Result<Object>(Result.ResultCode.SUCCESS.code,
                "insert success");
    }

    @Override
    public User getUserById(int id) {

        return  userRepository.findById(id).orElse(null);
    }

    @Override
    public List<User> getAllUser() {
        return Optional.
                ofNullable(userRepository.findAll())
                .orElse(Collections.emptyList());
    }

    @Override
    @Transactional
    public Result<Object> deleteUserByIdJpa(int id) {
        userRepository.deleteById(id);
        return new Result<Object>(Result.ResultCode.SUCCESS.code,
                "delete success");
    }
//    修改数据
    @Override
    @Transactional
    public Result<User> editUser(User user) {
        userRepository.saveAndFlush(user);
        return new Result<User>(Result.ResultCode.SUCCESS.code,"" +
                "edit success");
    }

    @Override
    public Page<User> getUsersBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        return getUsersBySpecification(searchBean);
    }

    @Override
    public User getUserByIdForSql(int id) {
        userRepository.getUserByIdForSql(id).setRoles(userRepository.getUserByIdForSql(id).getRoles());
        return userRepository.getUserByIdForSql(id);
    }

    @Override
    public  Result<User> getUserByUserNameAndPassword(String userName, String password) {
        User user =  userDao.getUserByUserNameAndPassword(userName, MD5Util.getMD5(password));
        if (user == null) {
            return new Result<User>(Result.ResultCode.FAILED.code,"帅哥错了重新来");
        }else {
            return new Result<User>(Result.ResultCode.SUCCESS.code,"帅哥对了你真棒！");
        }
    }


    @Override
    public Result<User> login(User user) {
        User temp = userDao.getUserByUserNameAndPassword(user.getUserName(),
                MD5Util.getMD5(user.getPassword()));
        if (temp != null) {
            return new Result<User>(Result.ResultCode.SUCCESS.code, "Success", temp);
        } else {
            return new Result<User>(Result.ResultCode.FAILED.code, "Failed");
        }

    }

    @Override
    public void logout() {
    }


    private Page<User> getUsersBySpecification(SearchBean searchBean) {
        Sort.Direction direction = StringUtils.isBlank(searchBean.getDirection()) ||
                searchBean.getDirection().toLowerCase().equals("asc") ?
                Sort.Direction.ASC : Sort.Direction.DESC;
        Sort sort = Sort.by(direction, searchBean.getOrderBy());
        Pageable Pageable = PageRequest.of(
                searchBean.getCurrentPage() - 1,
                searchBean.getPageSize(),
                sort);
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.and(
                        criteriaBuilder.greaterThan(
                                root.get("createDate").as(LocalDateTime.class),
                                LocalDateTime.of(2021, 8, 20, 0, 0)
                        ),
                        criteriaBuilder.or(
                                criteriaBuilder.between(root.get("id"),1, 10),
                                criteriaBuilder.like(
                                        root.get("userName").as(String.class),
                                        String.format("%%%s%%", searchBean.getKeyword())
                                )
                        )
                );
            }
        };
        return userRepository.findAll(specification, Pageable);
    }
}
